package com.core.data;

import com.core.enums.IntEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * IntEnum类型的枚举和数据库Integer的映射处理类
 */
public class IntEnumTypeHandler<T extends IntEnum> extends BaseTypeHandler<T> {

    private final Class<T> type;

    public IntEnumTypeHandler(Class<T> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        this.type = type;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        ps.setInt(i, parameter.getValue());
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        int dbResult = rs.getInt(columnName);
        Integer intResult = dbResult == 0 && rs.wasNull() ? null : dbResult;
        return intResult == null ? null : IntEnum.of(type, intResult);
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        int dbResult = rs.getInt(columnIndex);
        Integer intResult = dbResult == 0 && rs.wasNull() ? null : dbResult;
        return intResult == null ? null : IntEnum.of(type, intResult);
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        int dbResult = cs.getInt(columnIndex);
        Integer intResult = dbResult == 0 && cs.wasNull() ? null : dbResult;
        return intResult == null ? null : IntEnum.of(type, intResult);
    }
}
